<!-- src/views/BucketListPage.vue (最终优化版) -->
<template>
    <div class="bucket-list-page-container">
        <div class="page-header-title">Bucket 列表</div>
        <el-alert title="统计 Bucket 合计数据，平均延迟 1~3 小时..." type="info" show-icon :closable="false" class="info-alert" />
        <el-card shadow="never" class="action-card">
            <div class="action-bar">
                <div class="actions-left">
                    <!-- 【修改点 1】绑定点击事件 -->
                    <el-button type="primary" @click="createDrawerVisible = true">创建 Bucket</el-button>
                    <el-button @click="fetchBuckets">全部 Bucket</el-button>
                    <el-input placeholder="Bucket 名称" class="search-input">
                        <template #append><el-button :icon="Search" /></template>
                    </el-input>
                </div>
                <div class="actions-right">
                    <el-button :icon="Setting" circle />
                    <el-button :icon="Download" circle />
                    <el-button :icon="Refresh" circle @click="fetchBuckets" />
                </div>
            </div>
            <el-table :data="tableData" v-loading="isLoading" stripe style="width: 100%; margin-top: 20px;">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="Bucket 名称" sortable>
                    <template #default="scope">
                        <router-link :to="{ name: 'BucketContents', params: { bucketName: scope.row.name } }">
                            {{ scope.row.name }}
                        </router-link>
                    </template>
                </el-table-column>
                <el-table-column prop="region" label="地域" sortable>
                    <template #default="scope">
                        {{ getRegionDisplayName(scope.row.region) }}
                    </template>
                </el-table-column>
                <el-table-column prop="storage_class" label="存储类型" sortable />
                <el-table-column prop="size" label="容量" width="180" />
                <el-table-column prop="versioning" label="版本控制">
                    <template #default="scope">
                        <span>{{ scope.row.versioning }}</span><br />
                        <el-button type="primary" link @click="toggleVersioning(scope.row)"
                            :loading="scope.row.versioningLoading">
                            {{ scope.row.versioning === '已开启' ? '暂停' : '开启' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-bar">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="totalItems"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
        <CreateBucketDrawer v-model:visible="createDrawerVisible" @create-success="handleCreateSuccess" />

        <!-- ======================================================= -->
        <!-- == 【新增】用于确认版本控制操作的 Dialog 对话框       == -->
        <!-- ======================================================= -->
        <el-dialog v-model="versioningDialog.visible" title="注意事项" width="520px" class="versioning-dialog" align-center>
            <!-- 对话框的主体内容 -->
            <div class="dialog-content">
                <el-icon :size="24" color="#E6A23C" class="dialog-icon">
                    <WarningFilled />
                </el-icon>
                <p>暂停版本控制功能后，将会暂停在该Bucket内创建新的历史版本，数据删除后将无法找回，是否继续暂停版本控制？</p>
            </div>

            <!-- 对话框的页脚，包含按钮 -->
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="versioningDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="confirmToggleVersioning">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { Search, Setting, Download, Refresh, WarningFilled } from '@element-plus/icons-vue';
import { ref, onMounted, reactive } from 'vue';
import CreateBucketDrawer from '@/components/CreateBucketDrawer.vue';
import apiClient from '@/api';
import { ElMessage } from 'element-plus';

const tableData = ref([]);
const totalItems = ref(0);
const error = ref(null);
const isLoading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);
const createDrawerVisible = ref(false);

const regionMap = {
    'pri.idclt.fujian-zhihcs': '福建-智汇云',
};

// 2. 【新增】用于管理 Dialog 的响应式对象
const versioningDialog = reactive({
    visible: false,
    bucket: null, // 用于存储当前正在操作的 bucket 对象
});

const getRegionDisplayName = (regionCode) => {
    return regionMap[regionCode] || regionCode;
};

// 【修改点 3】fetchBuckets 函数现在会发送分页参数
const fetchBuckets = async () => {
    isLoading.value = true;
    error.value = null;
    try {
        const response = await apiClient.get('/api/v1/buckets', {
            params: {
                page: currentPage.value,
                limit: pageSize.value,
            }
        });
        console.log("fetchBuckets 被调用，获取到新数据:", response.data);
        tableData.value = response.data.items;
        totalItems.value = response.data.total;
    } catch (err) {
        console.error('加载存储桶失败:', err);
        error.value = '无法加载存储桶列表。';
        ElMessage.error('刷新存储桶列表失败！');
    } finally {
        isLoading.value = false;
    }
};

const handleSizeChange = (newPageSize) => {
    pageSize.value = newPageSize;
    currentPage.value = 1; // 改变每页条数时回到第一页
    fetchBuckets();
};

const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    fetchBuckets();
};

// 【修改点 2】添加成功回调函数
const handleCreateSuccess = () => {
    console.log('子组件通知：Bucket 创建成功！正在刷新列表...');
    fetchBuckets();
};

// 在 BucketListPage.vue 的 <script setup> 中，用这个版本替换旧的 toggleVersioning 方法

// 3. 【重构】toggleVersioning 方法
const toggleVersioning = (bucket) => {
    const isCurrentlyEnabled = bucket.versioning === '已开启';

    if (isCurrentlyEnabled) {
        // 如果是暂停操作，则打开对话框进行确认
        versioningDialog.bucket = bucket; // 保存要操作的 bucket 信息
        versioningDialog.visible = true;
    } else {
        // 如果是开启操作，则直接执行，无需确认
        // 为了代码复用，我们让它也走 confirmToggleVersioning 逻辑
        versioningDialog.bucket = bucket;
        confirmToggleVersioning();
    }
};

// 4. 【新增】用户点击对话框“确定”按钮后执行的函数
const confirmToggleVersioning = async () => {
    const bucket = versioningDialog.bucket;
    if (!bucket) return;

    const isCurrentlyEnabled = bucket.versioning === '已开启';
    const newStatus = isCurrentlyEnabled ? 'Suspended' : 'Enabled';
    const actionText = isCurrentlyEnabled ? '暂停' : '开启';

    try {
        // --- 核心API调用逻辑，与之前完全相同 ---
        bucket.versioningLoading = true; // 开始加载

        await apiClient.put(`/api/v1/buckets/${bucket.name}/versioning`, {
            status: newStatus,
        });

        ElMessage.success(`已成功${actionText}版本控制。`);
        fetchBuckets(); // 刷新列表

    } catch (error) {
        ElMessage.error(error.response?.data?.error || `操作失败`);
    } finally {
        // 无论成功失败，都关闭对话框并清除加载状态
        versioningDialog.visible = false;
        if (bucket.versioningLoading) {
            bucket.versioningLoading = false;
        }
    }
};

onMounted(fetchBuckets);
</script>

<style scoped>
/* 样式部分保持不变 */
.bucket-list-page-container {
    padding: 20px;
}

.info-alert {
    margin-bottom: 20px;
}

.action-card {
    margin-top: 20px;
}

.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.actions-left,
.actions-right {
    display: flex;
    gap: 10px;
    align-items: center;
}

.search-input {
    width: 240px;
}

.pagination-bar {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.page-header-title {
    font-size: 20px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 20px;
}

.size-cell {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.calculate-btn {
    margin-left: 8px;
}

.bucket-list-page {
    padding: 20px;
}

.dialog-content {
    display: flex;
    align-items: center;
    line-height: 1.6;
}

.dialog-icon {
    margin-right: 10px;
    flex-shrink: 0;
    /* 防止图标被压缩 */
}

/* 我们可以使用 :deep() 来修改 el-dialog 内部按钮的样式，比如焦点样式 */
/* :deep(.versioning-dialog .el-dialog__footer .el-button:focus) {
    outline: none;
} */
</style>